import { defineStore } from 'pinia'
import { showToast } from 'vant'
import api from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    isAdmin: localStorage.getItem('isAdmin') === '1'
  }),

  getters: {
    getToken: (state) => state.token,
    getUserInfo: (state) => state.userInfo,
    getIsAdmin: (state) => state.isAdmin
  },

  actions: {
    // 检查登录状态
    checkLoginStatus() {
      const token = localStorage.getItem('token')
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (token && userInfo.id) {
        this.setToken(token)
        this.setUserInfo(userInfo)
        this.setIsAdmin(userInfo.is_admin === 1)
        return true
      }
      return false
    },

    // 注册
    async register(userData) {
      try {
        const res = await api.user.register(userData)
        if (res.code === 0) {
          showToast('注册成功')
          return true
        }
        throw new Error(res.message || '注册失败')
      } catch (error) {
        console.error('注册失败:', error)
        showToast(error.message || '注册失败')
        throw error
      }
    },

    // 登录
    async login(username, password) {
      try { 
        const res = await api.user.login({ username, password })
        if (res.success) {
          const { token, userInfo } = res.data
          this.setToken(token)
          this.setUserInfo(userInfo)
          this.setIsAdmin(userInfo.isAdmin === 1)
          showToast('登录成功')
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        showToast(error.message || '登录失败')
        return false
      }
    },

    // 退出登录
    async logout() {
      try {
        await api.user.logout()
        
        this.clearUserData()
        showToast('已退出登录')
      } catch (error) {
        console.error('退出登录失败:', error)
        showToast('退出登录失败')
      }
    },

    // 清除用户数据
    clearUserData() {
      this.token = ''
      this.userInfo = {}
      this.isAdmin = false
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('isAdmin')
    },

    // 设置token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    // 设置管理员状态
    setIsAdmin(isAdmin) {
      this.isAdmin = isAdmin
      localStorage.setItem('isAdmin', isAdmin)
    }
  }
}) 